<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="用户管理" name="first">
            <el-button type="primary" @click="hAdd">+添加角色</el-button>

            <!-- 表格 -->
            <el-table :data="roles">
              <!-- 设置type属性为index即可显示从 1 开始的索引号 -->
              <el-table-column
                label="序号"
                type="index"
                :index="indexMethod"
                width="50"
              />
              <el-table-column label="角色名称" prop="name" width="200" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                  <el-button type="success">分配权限</el-button>
                  <el-button type="primary" @click="hEdit(scope.row)">
                    编辑
                  </el-button>
                  <el-button type="danger" @click="hDel(scope.row.id)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!--
              分页组件
              total: 总的数据条数(后端返回的)
              page-size: 每页显示几条
              @current-change:点击页面触发，它会自动传入当前的页码

              -->
            <el-pagination
              layout="prev, pager, next"
              :total="total"
              :current-page.sync="curPage"
              :page-size="pageParams.pageSize"
              @current-change="hCurrentChange"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="30%"
      :title="isEdit ? '编辑' : '添加'"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <el-form ref="form" label-width="80px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="form.description" />
        </el-form-item>
        <el-form-item>
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getRoles, deleteRole, addRole, editRole } from '@/api/settings'
export default {
  name: 'Settings',
  data () {
    return {
      activeName: 'first',
      curPage: 1,
      pageParams: {
        page: 1,
        pageSize: 2
      },
      total: 0,
      roles: [],
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: { name: [{ required: true, message: '角色名字不能为空', trigger: 'blur' }] },
      isEdit: false // 当前是否处于编辑
    }
  },
  computed: {
    isLastPage: function () {
      const maxNum = Math.ceil(this.total / this.pageParams.pageSize)
      return this.pageParams.page === maxNum
    },
    // 表格中最大的页码
    maxNum () {
      return Math.ceil(this.total / this.pageParams.pageSize)
    },
    // 最后一页是不是满的
    isLastPageFulled: function () {
      return this.total % this.pageParams.pageSize === 0
    }
  },
  created () {
    this.loadRoles()
  },
  methods: {
    indexMethod (index) {
      // (0 + 1) + (2 - 1 )* 2 == 3
      index = (index + 1) + (this.pageParams.page - 1) * this.pageParams.pageSize
      return index
    },
    // 用户点击了添加
    hAdd () {
      this.showDialog = true
      this.isEdit = false
    },
    async doAdd () {
      try {
        // 1. 调用接口
        const res = await addRole(this.form)
        // 2. 关闭弹层
        this.showDialog = false
        if (this.isLastPageFulled) {
          debugger
          this.pageParams.page = this.maxNum + 1
        } else {
          // 想查看最新添加的数据，要跳到最大页码
          this.pageParams.page = this.maxNum
        }
        // 3. 重发请求
        this.loadRoles()
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    // hSubmit () {
    //   this.$refs.form.validate(valid => {
    //     if (valid) {
    //       this.doAdd()
    //     }
    //   })
    // },
    async doDel (id) {
      console.log('要删除的id是', id)
      try {
        // 1. 删除
        const res = await deleteRole(id)
        console.log(res)
        if (this.roles.length === 1) {
          console.log('删除的是当前页的最后一条数据')
          this.pageParams.page--

          if (this.pageParams.page === 0) {
            this.pageParams.page = 1
          }
        }
        // 2. 更新页面
        this.loadRoles()
        // 3. 提示
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    hDel (id) {
      this.$confirm('确认要删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    async doEdit () {
      try {
        // 1. 调用接口
        const res = await editRole(this.form)
        // 2. 关闭弹层
        this.showDialog = false

        // 3. 重发请求
        this.loadRoles()
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    hSubmit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },

    hEdit (row) {
      console.log('hEdit...')
      // 1. 弹框
      this.showDialog = true
      // 2. 表单赋值
      // this.form = row
      this.form = { ...row }
      // 3. 更新编辑状态
      this.isEdit = true
    },
    async loadRoles () {
      try {
        // page, pageSize
        const res = await getRoles(this.pageParams.page, this.pageParams.pageSize)
        console.log(res)
        this.roles = res.data.rows
        this.total = res.data.total
        this.curPage = this.pageParams.page
      } catch (err) {
        console.log(err)
      }
    },
    hCurrentChange (curPage) {
      console.log('当前的页码', curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.loadRoles()
    },
    hClose () {
      // 弹层关闭了
      console.log('弹层关闭了')
      // 重置表单
      this.form = {}
      this.$refs.form.resetFields()
    }
  }
}
</script>
